package com.gongsir.controller;

import com.gongsir.utils.QiNiuUtil;
import com.gongsir.utils.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 码之泪殇
 * @date 2020/8/27 14:20
 * 到达胜利之前，无法回头
 */
@RestController
@Slf4j
public class FileUploadController {

    /**
     * 用此格式的日期对上传的图片进行分类
     */
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @PostMapping(path = "/upload")
    public ResponseData uploadFile(MultipartFile file) {
        ResponseData responseData = new ResponseData();
        if (file.isEmpty()) {
            responseData.setCode(0);
            responseData.setMsg("文件为空");
            return responseData;
        }
        String fromat = sdf.format(new Date());
        String fileName = fromat+"-"+file.getOriginalFilename();
        try {
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            String res = QiNiuUtil.upload2QiNiu(fileInputStream, fileName);
            if (res == null) {
                responseData.setCode(0);
                responseData.setMsg("文件上传失败");
            } else {
                responseData.setCode(1);
                responseData.setMsg("上传成功");
                responseData.putDataValue("url",res);
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return responseData;
    }
}
